package com.atguigu.gmall.order.listener;

import com.atguigu.gmall.common.util.Jsons;
import com.atguigu.gmall.order.biz.OrderBizService;
import com.atguigu.gmall.util.consts.MqConst;
import com.atguigu.gmall.util.service.RabbitService;
import com.atguigu.gmall.ware.WareStockResultMsg;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @author lfy
 * @Description 监听订单库存扣减结果
 * @create 2022-10-24 14:05
 */
@Service
public class OrderStockResultListener {


    @Autowired
    RabbitService rabbitService;

    @Autowired
    OrderBizService orderBizService;

    /**
     * 可以在声明注解的时候，不存在的队列等自动创建
     */
    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue(value = MqConst.WARE_ORDER_QUEUE,durable = "true",exclusive = "false",autoDelete = "false"),
                    exchange = @Exchange(value = MqConst.WARE_ORDER_EXCHANGE),
                    key = MqConst.ORDER_STOCK_QUEUE
            )
    })
    public void orderStockListen(Message message, Channel channel) throws IOException {
        long tag = message.getMessageProperties().getDeliveryTag();
        String json = new String(message.getBody());
        try{
            //修改订单的状态为 库存扣减的状态
            WareStockResultMsg resultMsg = Jsons.toObj(json, WareStockResultMsg.class);
            orderBizService.updateOrderStatusByStockResult(resultMsg);
            channel.basicAck(tag,false);
        }catch (Exception e){
            rabbitService.retry(channel,tag,json,5);
        }

    }
}
